<template>
	<view class="container">
		<view class="top-tab flex-item-center">
			<view class="tab-wrapper">
				<view class="tab-slider" :style="{ transform: `translateX(${index * 100}%)` }"></view>
				<view :class="{active: index === 0}" @click="switchTab(0)">{{ $t('shopmall.tabs.mall') }}</view>
				<view :class="{active: index === 1}" @click="switchTab(1)">{{ $t('shopmall.tabs.order') }}</view>
			</view>
		</view>

		<!-- 商城 -->
		<view v-if="index === 0" class="list-box">
			<view v-for="item in mallList" :key="item.id" class="items flex-item-center">
				<view class="goods-img">
					<image :src="item.imageUrl || '/static/logo.png'" mode="aspectFit"></image>
				</view>
				<view class="infos">
					<view class="name">{{ getLevelText(item.type) }}</view>
					<view class="price-box flex-just-between">
						<text class="price">{{ item.price ? `$${item.price}` : '$0.00' }}</text>
						<view class="button" @click="makeOrder(item)">{{ $t('shopmall.buttons.purchase') }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 订单 -->
		<view v-if="index === 1" class="order-box">
			<view class="sub-tab flex-item-center">
				<view class="sub-tab-wrapper">
					<view :class="{active: subIndex === 0}" @click="switchSubTab(0)">
						{{ $t('shopmall.subTabs.released') }}
					</view>
					<view :class="{active: subIndex === 1}" @click="switchSubTab(1)">
						{{ $t('shopmall.subTabs.completed') }}
					</view>
					<view class="sub-tab-slider" :style="{ transform: `translateX(${subIndex * 100}%)` }"></view>
				</view>
			</view>
			<view class="order-list-box">
				<view v-for="order in orderList" :key="order.id" class="order-item">
					<view class="top-info flex-just-between">
						<view class="order-num">{{ $t('shopmall.order.orderNumber') }}：{{ order.orderNo }}</view>
						<text>{{ getOrderStatusText(order.releaseState) }}</text>
					</view>
					<view class="center-info">
						<view class="goods-info flex-item-center">
							<view class="goods-img">
								<image :src="order.imageUrl || '/static/logo.png'" mode="aspectFit"></image>
							</view>
							<view class="infos">
								<view class="name">{{ order.description }}</view>
								<view class="price-box flex-just-between">
									<view class="price">$<text>{{ order.amount }}</text></view>
									<view class="num">x{{ order.nums ?? 1 }}</view>
								</view>
							</view>
						</view>
						<view class="pay-amount flex-item-center">{{ $t('shopmall.order.payableAmount') }}：<view
								class="price">$<text>{{ order.amount }}</text></view>
						</view>
					</view>
					<view class="bottom-price flex-just-between">
						<view>{{ $t('shopmall.order.releaseAmount') }}:$<text>{{ order.releasedAmount }}</text></view>
						<view class="right {{ order.status === 'completed' ? 'green' : '' }}">
							{{ $t('shopmall.order.releasedQuantity') }}:$<text>{{ order.releasedTotalAmount }}</text>
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view class="loading-more" v-if="loading">
					<text>{{ $t('shopmall.loading') }}</text>
				</view>

				<!-- 没有更多数据 -->
				<!-- 	<view class="no-more-data" v-if="!loading && hasMoreData === false && filteredOrders.length > 0">
					<text>{{ $t('shopmall.noMoreData') }}</text>
				</view> -->

				<!-- 空状态 -->
				<!-- <view class="empty-state" v-if="!loading && filteredOrders.length === 0">
					<image src="/static/empty.png" mode="aspectFit"></image>
					<text>{{ $t('shopmall.emptyOrders') }}</text>
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	import trainerApi from '@/api/trainer.js';
	export default {
		data() {
			return {
				index: 0, // 主标签索引 (0: 商城, 1: 订单)
				subIndex: 0, // 订单子标签索引 (0: 已发布, 1: 已完成)
				mallList: [], // 商城数据列表
				orderList: [], // 订单数据列表
				// 状态映射
				statusMap: {
					// released: 'released',
					// completed: 'completed',

					released: 1,
					completed: 2
				},
				// 分页相关
				page: {
					released: {
						current: 1,
						size: 15,
						hasMore: true
					},
					completed: {
						current: 1,
						size: 15,
						hasMore: true
					}
				},
				loading: false, // 是否正在加载
				refreshing: false // 是否正在刷新
			}
		},
		computed: {
			// // 过滤后的订单列表
			// filteredOrders() {
			// 	if (this.subIndex === 0) {
			// 		return this.orderList.filter(order => order.status === this.statusMap.released);
			// 	} else {
			// 		return this.orderList.filter(order => order.status === this.statusMap.completed);
			// 	}
			// },
			// 当前分类是否还有更多数据
			hasMoreData() {
				const type = this.subIndex === 0 ? 'released' : 'completed';
				return this.page[type].hasMore;
			}
		},
		mounted() {
			this.loadMallData(); // 初始化加载商城数据
		},
		methods: {
			// 切换主标签
			switchTab(index) {
				if (this.index === index) return; // 避免重复切换

				this.index = index;
				if (index === 0) {
					this.loadMallData();
				} else {
					// 重置订单分页
					this.resetOrderPage();
					this.loadOrderData(true);
				}
			},
			// 切换订单子标签
			switchSubTab(subIndex) {
				if (this.subIndex === subIndex) return; // 避免重复切换

				this.subIndex = subIndex;
				// 重置当前分类的分页
				this.resetCurrentOrderPage();
				this.loadOrderData(true);
			},
			// 重置订单分页
			resetOrderPage() {
				this.page = {
					released: {
						current: 1,
						size: 15,
						hasMore: true
					},
					completed: {
						current: 1,
						size: 15,
						hasMore: true
					}
				};
			},
			// 重置当前分类的分页
			resetCurrentOrderPage() {
				const type = this.subIndex === 0 ? 'released' : 'completed';
				this.page[type] = {
					current: 1,
					size: 15,
					hasMore: true
				};
			},
			// 加载商城数据
			loadMallData() {
				return trainerApi.getTrainerQualificationList().then(res => {
					if (res.code === 0) {
						this.mallList = res.data || [];
					} else {
						uni.showToast({
							title: this.$t('shopmall.toast.loadFailed'),
							icon: 'none'
						});
					}
				});
			},
			// 加载订单数据
			loadOrderData(isRefresh = false) {
				if (this.loading) return; // 避免重复加载

				const type = this.subIndex === 0 ? 'released' : 'completed';

				// 如果是刷新，重置分页
				if (isRefresh) {
					this.refreshing = true;
					this.page[type].current = 1;
				} else {
					// 如果没有更多数据，不继续加载
					if (!this.page[type].hasMore) return;
					this.loading = true;
				}

				const currentPage = this.page[type].current;

				return trainerApi.getTrainerQualificationOrderList({
					page: currentPage,
					limit: this.page[type].size,
					releaseState: this.subIndex == 0 ? 1 : 2
				}).then(res => {
					if (res.code === 0) {
						const list = res.data.list || [];
						const total = res.data.total || 0;

						// 判断是否还有更多数据
						const hasMore = list.length >= this.page[type].size && total > list.length * currentPage;
						this.page[type].hasMore = hasMore;

						// 更新数据
						if (isRefresh || currentPage === 1) {
							this.orderList = list;
						} else {
							this.orderList = [...this.orderList, ...list];
						}

						// 增加当前页码
						if (!isRefresh && list.length > 0) {
							this.page[type].current++;
						}

						// if (isRefresh) {
							// uni.showToast({
							// 	title: this.$t('shopmall.toast.refreshSuccess'),
							// 	icon: 'none'
							// });
						// }
					} else {
						uni.showToast({
							title: this.$t('shopmall.toast.loadFailed'),
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('加载订单失败', err);
					uni.showToast({
						title: this.$t('shopmall.toast.loadFailed'),
						icon: 'none'
					});
				}).finally(() => {
					this.loading = false;
					this.refreshing = false;

					// 如果是下拉刷新，停止刷新动画
					if (this.isPullDownRefresh) {
						uni.stopPullDownRefresh();
						this.isPullDownRefresh = false;
					}
				});
			},
			// 上拉加载更多
			loadMore() {
				if (!this.loading && !this.refreshing && this.hasMoreData) {
					this.loadOrderData(false);
				}
			},
			// 获取级别文本（带国际化）
			getLevelText(type) {
				const levelMap = {
					1: 'shopmall.level1',
					2: 'shopmall.level2',
					3: 'shopmall.level3'
				};
				return this.$t(levelMap[type] || 'shopmall.level1');
			},
			// 获取订单状态文本
			getOrderStatusText(status) {
				if (status === this.statusMap.released) {
					return this.$t('shopmall.order.status.released');
				} else if (status === this.statusMap.completed) {
					return this.$t('shopmall.order.status.completed');
				}
				return '';
			},
			// 购买商品
			makeOrder(item) {
				trainerApi.trainerQualificationOrder({
					"qualificationId": item.id
				}).then(res => {
					if (res.code === 0) {
						uni.showToast({
							title: this.$t('shopmall.toast.purchaseSuccess'),
							icon: 'success'
						});

						// 购买成功后刷新订单列表
						this.resetCurrentOrderPage();
						this.loadOrderData(true);
					} else {
						uni.showToast({
							title: res.message || this.$t('shopmall.toast.purchaseFailed'),
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('购买失败', err);
					uni.showToast({
						title: this.$t('shopmall.toast.purchaseFailed'),
						icon: 'none'
					});
				});
			}
		},
		// 页面下拉刷新
		onPullDownRefresh() {
			this.isPullDownRefresh = true;

			if (this.index === 0) {
				this.loadMallData().finally(() => {
					uni.stopPullDownRefresh();
				});
			} else {
				this.loadOrderData(true);
			}
		},
		// 页面上拉触底事件
		onReachBottom() {
			if (this.index === 1) {
				this.loadMore();
			}
		}
	}
</script>


<style lang="less" scoped>
	.container {
		padding-top: 15rpx;
		min-height: 93.4vh;

		.top-tab {
			margin: 0 auto;
			width: 298rpx;
			height: 80rpx;
			background-color: #ececec;
			border-radius: 40rpx;
			padding: 0 6rpx;
			font-size: 28rpx;

			.tab-wrapper {
				position: relative;
				display: flex;
				height: 100%;

				.tab-slider {
					position: absolute;
					left: 6rpx;
					top: 5rpx;
					width: 138rpx;
					height: 70rpx;
					background-color: #52A5F3;
					border-radius: 35rpx;
					z-index: 0;
					/* Place slider behind text */
					transition: transform 0.3s ease;
				}

				view {
					width: 138rpx;
					height: 70rpx;
					line-height: 70rpx;
					text-align: center;
					color: #999;
					cursor: pointer;
					z-index: 1;
					/* Ensure text is above slider */
					transition: color 0.3s ease;

					&.active {
						color: #fff;
					}
				}
			}
		}

		.list-box {
			margin-top: 64rpx;
			padding: 0 40rpx;
		}

		.goods-img {
			margin-right: 32rpx;
			width: 224rpx;
			height: 224rpx;
			box-shadow: 0rpx 20rpx 50rpx 0rpx rgba(0, 0, 0, 0.08);
			border-radius: 20rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			image {
				width: 70%;
				height: 70%;
			}
		}

		.items {
			margin-bottom: 40rpx;

			.infos {
				width: calc(100% - 257rpx);
			}

			.name {
				margin-bottom: 46rpx;
				font-size: 32rpx;
			}

			.price {
				font-size: 36rpx;
			}

			.button {
				width: 218rpx;
				height: 78rpx;
				line-height: 78rpx;
				background-color: #52A5F3;
				border-radius: 39rpx;
				font-size: 28rpx;
				text-align: center;
				color: #fff;
				cursor: pointer;
				transition: background-color 0.3s ease;

				&:hover {
					background-color: #3b8cdb;
				}
			}
		}

		.order-box {
			background-color: #F4F4F4;
			min-height: 86.2vh;

			.sub-tab {
				height: 120rpx;
				font-size: 30rpx;
				color: #A2A2A2;
				background-color: #fff;

				.sub-tab-wrapper {
					position: relative;
					display: flex;
					height: 100%;
					width: 100%;

					view {

						// 胡乱加的
						margin-top: 35rpx;

						flex: 1;
						text-align: center;
						position: relative;
						cursor: pointer;
						transition: color 0.3s ease;
						z-index: 1;
						/* Ensure text is above slider */

						&.active {
							color: #52A5F3;
						}
					}

					.sub-tab-slider {
						position: absolute;
						bottom: 0;
						width: 50%;
						height: 8rpx;
						background-color: #52A5F3;
						border-radius: 4rpx;
						z-index: 0;
						/* Place slider behind text */
						transition: transform 0.3s ease;
					}
				}
			}

			.order-list-box {
				padding: 40rpx;

				.order-item {
					padding: 0 26rpx;
					background-color: #fff;
					border-radius: 20rpx;
					font-size: 28rpx;
					margin-bottom: 20rpx;

					.goods-img {
						margin-right: 20rpx;
						width: 160rpx;
						height: 160rpx;
					}

					.top-info {
						height: 100rpx;
						font-size: 24rpx;
						border-bottom: 2rpx solid rgba(204, 204, 204, .3);

						.order-num {
							font-size: 28rpx;
							color: #9C9C9C;
						}
					}

					.price {
						color: #E82020;

						text {
							font-size: 40rpx;
						}
					}

					.center-info {
						padding: 16rpx 0 50rpx;

						.infos {
							width: calc(100% - 180rpx);
						}

						.name {
							margin-bottom: 38rpx;
							font-size: 32rpx;
						}

						.num {
							color: #9C9C9C;
						}

						.pay-amount {
							margin-top: 64rpx;
							justify-content: flex-end;
						}
					}

					.bottom-price {
						height: 124rpx;
						border-top: 2rpx solid rgba(204, 204, 204, .3);
						font-size: 24rpx;

						.right {
							color: #E00F0F;

							&.green {
								color: #1A981F;
							}
						}
					}
				}
			}
		}
	}
</style>